#!/usr/bin/env python3
import os
import json
import psutil
import socket
import traceback

class Path:
    homePath = os.path.expanduser('~')
    programPath = os.path.split(os.path.realpath(__file__))[0]  # 返回 string
    def __init__(self) -> None:
        pass

class File:
    filePath = ""
    def __init__(self, filePath: str) -> None:
        self.filePath = filePath

    def read(self) -> str:
        file = open(self.filePath, "r")
        value = file.read()
        file.close()
        return value

    def write(self, things) -> str:
        file = open(self.filePath, "w")
        file.write(things)
        file.close()


class Program:
    version = ""
    def __init__(self) -> None:
        pass

    def printVersion(self) -> None:
        print(self.version)

class VM:
    memory = 4096
    diskPath = ""
    def __init__(self, diskPath: str) -> None:
        self.diskPath = diskPath
        # 自动计算内存
        memory = psutil.virtual_memory()
        self.memory = int(float(memory.total) / 1024 / 1024 / 3)
    
    def run(self) -> int:
        return os.system(f"kvm -m {self.memory} -drive id=disk,file={self.diskPath},if=none -device ahci,id=ahci -device ide-hd,drive=disk,bus=ahci.0 -netdev user,id=ndev.0,hostfwd=tcp::5555-:3389,hostfwd=tcp::5556-:3389 -device e1000,netdev=ndev.0 -soundhw all")

    def connect(self, user="wine-runner", password="123456") -> int:
        return os.system(f"rdesktop 127.0.0.1:5555 -x l -u \"{user}\" -p \"{password}\" -f -a 32 -r clipboard:PRIMARYCLIPBOARD -r sound:remote -r disk:ROOT=/ -r disk:HOME={Path().homePath}")

class Net:
    def __init__(self, ip) -> None:
        self.ip = ip

    def checkPort(self, port) -> bool:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            s.connect((self.ip, port))
            s.shutdown(2)
            return True
        except:
            return False

    def install(self, path: str) -> bool:
        s = socket.socket()
        try:
            s.connect((self.ip, 56678))
            s.send(path.encode("utf-8"))
            while True:
                # 等待情况
                value = s.recv(1024).decode("utf-8")
                if "Error" in value:
                    s.close()
                    return False
                elif "OK" in value:
                    s.close()
                    return True
                print(f"\r{value}", end="")
        except:
            return False